<?php

namespace App\Services;

use App\Exceptions\BusinessException;
use App\Models\BaseModel;
use App\Models\Camp;
use App\Models\Food;
use App\Models\Label;

class FoodService extends BaseService
{
    /**
     * 美食列表
     * @param $page
     * @param $pageSize
     * @param $keyword
     * @param $filterId
     * @return array
     */
    public function list($page, $pageSize, $keyword = '', $filterId = 0)
    {
        // 设置对象
        $model = Food::query();
        // 关键词
        if ($keyword) {
            $model = $model->where('food_name', 'like', '%' . $keyword . '%');
        }
        // 筛选
        if ($filterId) {
            $model = $model->whereRaw('FIND_IN_SET(?, filter_ids)', [$filterId]);
        }
        // 状态
        $model = $model->where('status', BaseModel::STATUS_ENABLE);
        // 获取列表
        $result = $model
            ->orderBy('sort', 'desc')
            ->orderBy('id', 'desc')
            ->paginate($pageSize, ['id', 'food_name', 'food_desc', 'food_img', 'food_price', 'filter_ids', 'label_ids', 'stock'], 'page', $page);

        $labelNames = Label::query()->pluck('label_name', 'id') ?? [];
        $result->getCollection()->transform(function ($item) use ($labelNames) {
            $item = json_decode($item, true);
            $item['food_img'] = storageFirst($item['food_img']);
            $labelIds = explode(',', $item['label_ids']);
            $item['label_name'] = $labelNames[$labelIds[0]] ?? '';
            return $item;
        });

        return $this->successPage($result);
    }

    /**
     * 美食详情
     * @param $foodId
     * @return array
     * @throws BusinessException
     */
    public function detail($foodId)
    {
        // 获取数据
        $data = Food::query()->where('id', $foodId)->first();
        if (!$data) {
            $this->throwBusinessException('美食不存在');
        }
        $data = $data->toArray();

        $data['food_img'] = storageMulti($data['food_img']);
        $data['food_details'] = json_decode($data['food_details'], true) ?? [];
        // 标签
        $labelNames = Label::query()->pluck('label_name', 'id') ?? [];
        $labelIds = explode(',', $data['label_ids']);
        $data['label_name'] = [];
        foreach ($labelIds as $labelId) {
            $data['label_name'][] = $labelNames[$labelId] ?? '';
        }
        // 餐厅
        $camp = Camp::query()->first(['eat_lng', 'eat_lat', 'eat_time'])->toArray();

        return array_merge($data, $camp);
    }
}
